package middleware

import (
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// MemberService 会员服务接口
type MemberService interface {
	// 验证用户Token并获取会员信息
	VerifyToken(token string) (userId int64, isMember bool, expireTime time.Time, err error)
}

// MemberAuthMiddleware 会员权限验证中间件
func MemberAuthMiddleware(memberService MemberService) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    403,
				"message": "未登录",
			})
			c.Abort()
			return
		}

		// 提取Token（假设格式为 "Bearer <token>"）
		parts := strings.SplitN(authHeader, " ", 2)

		// 验证Token
		userId, isMember, expireTime, _ := memberService.VerifyToken(parts[1])

		// 检查是否为会员
		if !isMember {
			c.JSON(http.StatusForbidden, gin.H{
				"code":    403,
				"message": "您不是会员，无法观看此内容",
			})
			c.Abort()
			return
		}

		// 检查会员是否过期
		if time.Now().After(expireTime) {
			c.JSON(http.StatusForbidden, gin.H{
				"code":    401,
				"message": "您的会员已过期",
			})
			c.Abort()
			return
		}

		c.Set("userId", userId)
		c.Next()
	}
}

//在路由中使用中间件：
//// 注册需要会员权限的路由
//func SetupMemberRoutes(router *gin.Engine, seriesHandler *api.SeriesHandler, memberService MemberService) {
//	seriesGroup := router.Group("/api/v1/series")
//	{
//		// 普通接口不需要会员权限
//		seriesGroup.GET("/:id/info", seriesHandler.GetSeriesInfo)
//
//		// 播放接口需要会员权限
//		seriesGroup.GET("/:id/play", middleware.MemberAuthMiddleware(memberService), seriesHandler.PlaySeries)
//	}
//}
